package services;

import mapper.SmbmsUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.SmbmsUser;
import pojo.SmbmsUserExample;

import java.util.List;

/**
 * 用户服务层接口实现类，交给Spring管理
 */
@Service
public class UserServices {
//    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//    SmbmsUserMapper userMapper = context.getBean(SmbmsUserMapper.class);
    /**
     * Spring已经整合Mybatis，从Spring容器中取Mapper对象
     */
    @Autowired
    SmbmsUserMapper userMapper;

    /**
     * 登录
     * @param loginUser
     * @return
     */
    public SmbmsUser getUserByLogin(SmbmsUser loginUser) {
        SmbmsUserExample example = new SmbmsUserExample();
        SmbmsUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsercodeEqualTo(loginUser.getUsercode());
        criteria.andUserpasswordEqualTo(loginUser.getUserpassword());
        List<SmbmsUser> userList = userMapper.selectByExample(example);
        if (!userList.isEmpty()){
            return userList.get(0);
        }else {
            return null;
        }
    }

    /**
     * 获取所有用户
     * @return 用户列表
     */
    public List<SmbmsUser> getAllUser(){
        return userMapper.selectByExample(null);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public int addUser(SmbmsUser user){
        return userMapper.insert(user);
    }

    /**
     * 判断登录名是否存在
     * @param usercode
     * @return
     */
    public boolean userCodeIsExist(String usercode){
        SmbmsUserExample example = new SmbmsUserExample();
        SmbmsUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsercodeEqualTo(usercode);
        List<SmbmsUser> userList = userMapper.selectByExample(example);
        if (userList.isEmpty()){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 搜索用户
     * @param user
     * @return
     */
    public List<SmbmsUser> getUserBySearch(SmbmsUser user){
        SmbmsUserExample example = new SmbmsUserExample();
        SmbmsUserExample.Criteria criteria = example.createCriteria();
        if (user.getUsername() != null && !user.getUsername().equals("")) {
            criteria.andUsernameLike("%" + user.getUsername() + "%");
        }
        if (user.getUserrole() != null && user.getUserrole() != 0) {
            criteria.andUserroleEqualTo(user.getUserrole());
        }
        return userMapper.selectByExample(example);
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    public int modifyPassword(SmbmsUser user,String newPassword){
        SmbmsUserExample example = new SmbmsUserExample();
        SmbmsUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(user.getId());
        user.setUserpassword(newPassword);
        return userMapper.updateByExample(user,example);
    }
}
